import numpy as np
import matplotlib.pyplot as plt


#del的用法。


def loadDataSet(file):
    """
    读取文件。分数据和标签。
    :param file:
    :return:
    """
    dataMat=[];labelMat=[]
    fr=open(file)
    for line in fr.readlines():
        lineArr=line.strip().split()
        dataMat.append([1.0,float(lineArr[0]),float(lineArr[1])])
        labelMat.append(int(lineArr[2]))

    return dataMat,labelMat

def sigmoid(inX):
    """
    sigmoid函数
    :param inX:
    :return:
    """
    return 1.0/(1+np.exp(-inX))

def gradAscent(dataMatIn,clsssLabels):
    dataMatrix=np.mat(dataMatIn)
    labelMat=np.mat(clsssLabels).transpose()
    # print(labelMat)
    # print('labelMat.detype',labelMat.dtype)
    m,n=dataMatrix.shape
    alpha=0.001#学习率
    maxCycle=500#迭代次数
    weights=np.ones((n,1))
    # print(labelMat.dtype)

    for k in range(maxCycle):
        h=sigmoid(dataMatrix*weights)

        error=(labelMat-h)
        weights=weights+alpha*dataMatrix.transpose()*error
        # print('type_weights',type(weights))
    return weights









def plotBestFit(wei):
    """
    画图函数。
    :param wei:
    :return:
    """
    test=np.array(0)
    if(type(wei)!=type(test)):
        weights=wei.getA() #将MAT变成array
    else:
        weights=wei
    dataMat,labelMat=loadDataSet('testSet.txt')
    dataArr=np.array(dataMat)
    n=np.shape(dataArr)[0]
    xcord1=[];ycord1=[]
    xcord2=[];ycord2=[]
    for i in range(n):
        if(int(labelMat[i])==1):
            xcord1.append(dataArr[i,1]);ycord1.append(dataArr[i,2])
        else:
            xcord2.append(dataArr[i,1]);ycord2.append(dataArr[i,2])

    plt.figure(0)
    plt.subplot(111)
    plt.scatter(xcord1,ycord1,s=30,c='red',marker='s')
    plt.scatter(xcord2,ycord2,s=30,c='green')
    x=np.arange(-3.0,3.0,0.1)
    y=(-weights[0]-weights[1]*x)/weights[2]
    plt.plot(x,y)
    plt.xlabel('X1');plt.ylabel('X2')
    plt.show()

def stoGradAscent0(dataMatrix,classLabels):
    '''
    随机梯度第一版。
    :param dataMatrix:
    :param classLabels:
    :return:
    '''
    m,n=np.shape(dataMatrix)
    alpha=0.01
    weights=np.ones(n)
    for i in range(m):
        h=sigmoid(sum(dataMatrix[i]*weights))
        error=classLabels[i]-h
        weights=weights+alpha*error*dataMatrix[i]
    return weights

def stocGradAscent1(dataMatrix, classLabels, numIter=150):
    m,n = np.shape(dataMatrix)
    weights = np.ones(n)   #initialize to all ones
    for j in range(numIter):
        dataIndex = range(m)
        # print(dataIndex)
        for i in range(m):
            alpha = 4/(1.0+j+i)+0.0001    #apha decreases with iteration, does not
            randIndex = int(np.random.uniform(0,len(dataIndex)))#go to 0 because of the constant
            # print(len(dataIndex))
            h = sigmoid(sum(dataMatrix[randIndex]*weights))
            error = classLabels[randIndex] - h
            weights = weights + alpha * error * dataMatrix[randIndex]
            del (list(dataIndex)[randIndex])
    return weights



def classifyVector(inX, weights):
    """
    分类预测
    :param inX:
    :param weights:
    :return:
    """
    prob = sigmoid(sum(inX*weights))
    if prob > 0.5: return 1.0
    else: return 0.0


def colicTest():
    frTrain = open('horseColicTraining.txt'); frTest = open('horseColicTest.txt')
    trainingSet = []; trainingLabels = []
    for line in frTrain.readlines():
        currLine = line.strip().split('\t')
        lineArr =[]
        for i in range(21):
            lineArr.append(float(currLine[i]))
        trainingSet.append(lineArr)
        trainingLabels.append(float(currLine[21]))
    trainWeights = stocGradAscent1(np.array(trainingSet), trainingLabels, 1000)#计算回归系数向量。
    errorCount = 0; numTestVec = 0.0
    for line in frTest.readlines():
        numTestVec += 1.0
        currLine = line.strip().split('\t')
        lineArr =[]
        for i in range(21):
            lineArr.append(float(currLine[i]))
        if int(classifyVector(np.array(lineArr), trainWeights))!= int(currLine[21]):
            errorCount += 1
    errorRate = (float(errorCount)/numTestVec)
    print ("the error rate of this test is: %f" % errorRate)
    return errorRate

def multiTest():
    numTests = 10; errorSum=0.0
    for k in range(numTests):
        errorSum += colicTest()
    print ("after %d iterations the average error rate is: %f" % (numTests, errorSum/float(numTests)))
######################################
 
 
# test1：读取数据。然后用梯度上升法来拟合曲线
# data,label=loadDataSet('testSet.txt')
# weights=gradAscent(data, label)
# plotBestFit(weights)

######################################
# data,label=loadDataSet('testSet.txt')
# weights=stocGradAscent1(np.array(data),label)
# plotBestFit(weights)



######################################
multiTest()